package com.yesep.learn.netty.server.dispatcher;

import java.net.SocketAddress;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.yesep.learn.netty.protocol.util.CommandUtil;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;

/**
 * 请求分排器
 */
@Component
public class RequestDispatcher implements ApplicationContextAware {
	private static final Logger log = LoggerFactory.getLogger(RequestDispatcher.class);
	/**
	 * Spring上下文
	 */
	private ApplicationContext applicationContext;

	/**
	 * 发送
	 *
	 * @param ctx
	 *            channelHandlerContext
	 * @param data:上传的报文
	 */
	public void dispatcher(final ChannelHandlerContext ctx, final String data) {

		Channel channel = ctx.channel();
		//SocketAddress localAddr = channel.localAddress();
		SocketAddress remoteAddr = channel.remoteAddress();
		log.info("通道ID : {} remoteAddress:{} 处理报文 : {}", channel.id(), remoteAddr, data);

		Runnable runnable = () -> {
			CommandUtil.execute(ctx, data);
		};
		Thread thread = new Thread(runnable);
		thread.start();

	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}
}
